<template>
  <div class="employees-container">
    <!-- 分享展示, 预览的二维码的弹层 -->
    <el-dialog title="二维码" :visible="showCodeDialog" width="30%" @close="closeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 角色弹层 -->
    <assign-role :show-role-dialog="showRoleDialog" :user-id="userId" @update:showRoleDialog="showRoleDialog = $event" />
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: 16 条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="头像" sortable="">
            <template #default="{row}">
              <img v-imgerror="defaultImage" class="staff" :src="row.staffPhoto || defaultImage" alt="" @click="clickShowCodeDialog(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template #default="{ row }">
              {{ row.timeOfEntry | formatDate('/') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="pageSize"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <add-employee :show-dialog.sync="showDialog" @add-employee="getEmployeeList" />
  </div>
</template>

<script>
import QrCode from 'qrcode'
import EmployeeEnum from '@/api/constant/employees'
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import addEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters'
import AssignRole from './components/assign-role.vue'
// import dayjs from 'dayjs'
export default {
  name: 'Employees',
  components: { addEmployee, AssignRole },
  // filters: {
  //   formatDate(value, flag = '/') {
  //     return dayjs(value).format(`YYYY${flag}MM${flag}DD`)
  //   }
  // },
  data() {
    return {
      showCodeDialog: false,
      defaultImage: 'https://ly666-1315920906.cos.ap-shanghai.myqcloud.com/%E5%8A%A8%E6%BC%AB.jpeg',
      showRoleDialog: false,
      list: [],
      page: 1, // 当前页
      pageSize: 10, // 每页条数
      total: 0, // 总数
      loading: false,
      showDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    clickShowCodeDialog(url) {
      // console.log(url)
      if (!url) {
        return this.$message.error('没有上传头像')
      }
      // dom的更新不是同步的 打开了对话框，因为dom更新不是同步的所以没有获取到canvas元素,注意，showCodeDialog需要先显示出来，在处理nextTick
      this.showCodeDialog = true
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    // 关闭弹窗
    closeDialog() {
      this.showCodeDialog = false
    },
    editRole(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    async getEmployeeList() {
      this.loading = true
      const { data } = await reqGetEmployeeList(this.page, this.pageSize)
      const { total, rows } = data
      this.total = total
      this.list = rows
      this.loading = false
    },
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getEmployeeList()
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === +cellValue)
      return obj ? obj.value : '未知'
    },
    delEmployee(id) {
      this.$confirm('确定要删除该员工?', '温馨提示').then(async() => {
        await reqDelEmployee(id)
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success('删除成功')
        this.getEmployeeList()
      }).catch(() => {
        console.log('取消')
      })
    },
    // 导出excel
    handleDownload() {
      // 懒加载。原因因为这个文件很大，然后导出功能也不是经常使用
      import('@/vendor/Export2Excel').then(async excel => {
        // merges就是个数组，但他有特殊的写法['X1:X2', 'Y1:Y2', 'Z1:Z2']，处理的是合并
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        // multiHeader二维数组 处理的标题
        const multiHeader = [['姓名', '主要信息', '      ', '      ', '       ', '   ', '部门']]
        const header = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
        const headersRelations = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        // 我们不能直接把list赋值给我们data，因为data是二维数组，但我们的list对象数组
        // 我们list是当前页的
        const { data: { rows }} = await reqGetEmployeeList(1, this.total)
        console.log(rows)
        // const data = rows; // 不能处理，原因还是我们需要二维数组
        // const header = ['序号', '姓名', '年龄']
        // // 1 张三 18
        // // 2 李四 20
        // const data = [
        //   [1, '张三', 18],
        //   [2, '李四', 20]
        // ]
        const data = this.formatJson(rows, header, headersRelations)
        // console.log(data)
        excel.export_json_to_excel({
          header,
          data,
          filename: '福全',
          merges,
          multiHeader
        })
      })
    },
    // 将对象数组转换成二维数组
    formatJson(rows, header, headersRelations) {
      const result = []
      rows.forEach(row => {
        // 为了组成二维数组，写一个新的数组
        const arr = []
        // console.log(row)
        header.forEach(key => {
          const englishKey = headersRelations[key]
          // console.log({ row, englishKey })
          // console.log(row[englishKey])
          // const value = row[englishKey]
          let value = row[englishKey]
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = formatDate(value, '/')
          }
          if (englishKey === 'formOfEmployment') {
            value = EmployeeEnum.hireType.find(item => {
              return item.id === +value
            })?.value || '未知'
          }
          if (englishKey === 'departmentName') {
            value = value || '未知'
          }
          arr.push(value)
        })
        // arr.push(row)//不对
        result.push(arr)
      })
      return result
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
